package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"mytest/code"
	"mytest/database"
	"mytest/flower-order/model"
	"mytest/util"
	"time"
)

type UserController struct {
}

func (t *UserController) Index(c *gin.Context) {
	var userList []*model.User
	var formHelper util.FormHelper
	params := [][]string{
		{"page", "int", "num|has"},
		{"limit", "int", "num|has"},
		{"searchParams", "string-no-filter"},
	}
	paramMap, err := formHelper.Params(params, c)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	conditions := " 1=1 "
	if len(paramMap["searchParams"].(string)) > 0 {
		searchParams := make(map[string]string)
		err = json.Unmarshal([]byte(paramMap["searchParams"].(string)), &searchParams)
		if err != nil {
			c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
			return
		}
		for k, v := range searchParams {
			if v == "" {
				continue
			}
			switch k {
			case "vx":
				fallthrough
			case "name":
				fallthrough
			case "mobile":
				conditions += fmt.Sprintf(" and `%s` like  '%%%s%%' ", k, v)
			default:
				conditions += fmt.Sprintf(" and `%s` =  '%s' ", k, v)
			}
		}
	}
	serialNum := c.DefaultQuery("serial_num", "")
	if len(serialNum) > 0 {
		conditions += fmt.Sprintf(" and `serial_num` =  '%s' ", serialNum)
	}
	name := c.DefaultQuery("name", "")
	if len(name) > 0 {
		conditions += fmt.Sprintf(" and `name` like  '%%%s%%' ", name)
	}

	limit := paramMap["limit"].(int)
	page := paramMap["page"].(int)
	offset := (page - 1) * limit
	var count int64
	database.DB.Debug().Model(model.User{}).Select("id").Where(conditions).Count(&count)

	query := database.DB.Debug().Model(model.User{}).Preload("Img")

	//category := c.DefaultQuery("category", "")
	//if len(category) > 0 {
	//	flag = true
	//	query = query.Preload("Category", "name like '%"+category+"%'")
	//} else {
	//	query = query.Preload("Category")
	//}

	err = query.Where(conditions).Limit(limit).Offset(offset).Order("serial_num asc").Find(&userList).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	response := util.ReturnSuccess(userList)
	response["count"] = count
	c.JSON(code.Success, response)
	return
}

func (t *UserController) Show(c *gin.Context) {
	var user model.User
	var formHelper util.FormHelper
	params := [][]string{
		{"id", "string", "required|num"},
	}
	paramMap, err := formHelper.Params(params, c)
	if err != nil {
		c.JSON(code.Success, err.Error())
		return
	}
	err = database.DB.Debug().Model(model.User{}).
		Preload("Category").
		Preload("Img").
		Where("id = ?", paramMap["id"]).
		First(&user).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(user))
	return
}

func (t *UserController) Add(c *gin.Context) {
	var user model.User
	err := c.BindJSON(&user)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	nowTimeStr := time.Now().Local().Format(util.TimeLayout)
	user.CreatedAt = nowTimeStr
	user.UpdatedAt = nowTimeStr
	//ddd, _ := base64.StdEncoding.DecodeString(tuashu.ImgPath) //生成图片文件并写入到buffer
	//bbb := bytes.NewBuffer(ddd)
	//m, _, err := image.Decode(bbb) //图片解码
	//rgbImg := m.(*image.YCbCr)
	//subImg := rgbImg.SubImage(image.Rect(0, 0, 200, 200)).(*image.YCbCr) //图片裁剪
	//f, _ := os.Create("D:\\GoProject\\src\\test.jpeg")                   //创建文件
	//defer f.Close()
	//err = jpeg.Encode(f, subImg, nil)
	//user.ImgPath = "D:\\GoProject\\src\\test.jpeg"
	err = database.DB.Debug().Model(model.User{}).Create(&user).Error
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(nil))
	return
}

func (t *UserController) Edit(c *gin.Context) {
	var dataMap map[string]interface{}
	err := c.BindJSON(&dataMap)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	dataMap["updated_at"] = time.Now().Local().Format(util.TimeLayout)
	id := int(dataMap["id"].(float64))
	delete(dataMap, "id")
	delete(dataMap, "img")
	delete(dataMap, "category")
	delete(dataMap, "deleted_at")
	delete(dataMap, "created_at")
	err = database.DB.Debug().Model(&model.User{Id: id}).Updates(dataMap).Error
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(nil))
	return
}
